package com.hub.esdemo.config;

import lombok.Data;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @ author 飞天蝙蝠
 * @ date & time 2024/12/30 8:46
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class ElasticsearchConfig {

    private List<String> urlList;

    private String esUsername;

    private String esPassword;

    /**
     * scroll查询数量
     */
    private int scrollSize;


    @Bean
    public RestHighLevelClient elasticsearchClient() {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(esUsername, esPassword));

        RestClientBuilder builder = RestClient.builder(
                        urlList.stream().map(ElasticsearchConfig::transform).toArray(HttpHost[]::new))
                .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));

        return new RestHighLevelClient(builder);
    }

    /**
     * 将节点url转为HttpPost
     *
     * @param url
     * @return
     */
    private static HttpHost transform(String url) {
        String[] urlArr = url.split(":");
        int port = (urlArr.length == 2) ? Integer.parseInt(urlArr[1]) : 9200;
        return new HttpHost(urlArr[0], port);
    }

}
